package com.joker.storehelper.client.android.storage;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.joker.storehelper.client.android.R;

import java.util.List;

/**
 * 使用recycler view代替list view
 * Created by Administrator on 2018/1/12.
 */

public class GoodsListAdapter extends RecyclerView.Adapter<GoodsListAdapter.ViewHolder> implements View.OnClickListener {

    private List<Goods> goodsList;
    private OnItemClickListener mItemClickListener;
    private Context mContext;

    GoodsListAdapter(Context context,List<Goods> goods) {
        this.mContext = context;
        this.goodsList = goods;
    }

    @Override
    public void onClick(View v) {
        if (mItemClickListener!=null){
            mItemClickListener.onItemClick((Integer) v.getTag());
        }
    }

    public Goods getItem(int position) {
        return goodsList.get(position);
    }

    public interface OnItemClickListener{
        void onItemClick(int position);
    }
    public void setItemClickListener(OnItemClickListener itemClickListener) {
        mItemClickListener = itemClickListener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.store_goods_list_item,parent,false);
        view.setOnClickListener(this);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Goods goods = goodsList.get(position);
        holder.itemView.setTag(position);
        if (goods != null) {
            holder.tv.setText(goods.getName());
            if (goods.getBrand() != null) {
                holder.brandTv.setText(goods.getBrand().getName());
            }else{
                holder.brandTv.setText("");
            }
            if (goods.getCnt() == null) {
                goods.setCnt(0L);
            }
            holder.cntTv.setText(String.format("库存:%s", String.valueOf(goods.getCnt())));

        }
    }

    @Override
    public int getItemCount() {
        return goodsList.size();
    }

    public void nextPage(List<Goods> goods){
        goodsList.addAll(goods);
        notifyDataSetChanged();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tv;
        TextView brandTv;
        TextView cntTv;

        ViewHolder(View itemView) {
            super(itemView);
            tv = itemView.findViewById(R.id.store_goods_list_item_label);
            brandTv = itemView.findViewById(R.id.goods_list_item_brand);
            cntTv = itemView.findViewById(R.id.goods_list_item_cnt);
        }
    }
}
